package org.hyOnline.ebay
{
	import flash.events.*;
	import flash.external.ExternalInterface;
	import flash.net.*;

	public class ClientCollector
	{
		private static const JSFun:String="function hyGetClient(){" +
			"var obj = new Object();" +
			"obj.href = window.location.href;" +
			"obj.referrer = window.document.referrer;" +
			"var main = window.document.getElementById('mainContent');" +
			"if(main!=null){" +
			"obj.title = main.firstChild.innerHTML;" +
			"}else{" +
			"obj.title = 'unknown title';" +
			"}" +
			"return obj;" +
			"}";
		private static const CollectorURL:String = 'http://www.happyfashion.com.au/externalfile/ebayCollector.php';
		public function doCollect():void{
			try{
				var obj:Object = ExternalInterface.call(JSFun);
				var vars:URLVariables = new URLVariables();
				vars.data = JSON.stringify(obj);
				var loader:URLLoader = new URLLoader();
				var req:URLRequest = new URLRequest(CollectorURL);
				req.method = URLRequestMethod.POST;
				req.data = vars;
				configureListeners(loader);
				loader.load(req);
				
			}catch(e:Error){
				trace(e.toString()+":"+e.message);
			}			
		}
		private function configureListeners(dispatcher:IEventDispatcher):void {
			dispatcher.addEventListener(Event.COMPLETE, completeHandler);
			dispatcher.addEventListener(Event.OPEN, openHandler);
			dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		private function completeHandler(event:Event):void {
			var loader:URLLoader = URLLoader(event.target);
			try{
				var data:Object = JSON.parse(loader.data);
			}catch(error:Error){
				//JsForHfash.println("Unable to parse json");
				JsForHfash.println(loader.data);
			}
			
		}
		private function openHandler(event:Event):void {
			trace("openHandler: " + event);
		}
		
		private function progressHandler(event:ProgressEvent):void {
			trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
		}
		
		private function securityErrorHandler(event:SecurityErrorEvent):void {
			trace("securityErrorHandler: " + event);
		}
		
		private function httpStatusHandler(event:HTTPStatusEvent):void {
			trace("httpStatusHandler: " + event);
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void {
			trace("ioErrorHandler: " + event);
		}
	}
}